DSFX.Tweener =
{
	tweens: [], 
	isTweening: false,
	thread: null,
	fps: 200,
	
	register: function( tween )
	{
		this.tweens.push( tween );
		tween.start();
		this.start();
	},
	
	unregister: function( tween )
	{
		for ( var i = 0, tweenCount = this.tweens.length; i < tweenCount; i++ ) 
		{
			if ( this.tweens[i] == tween )
			{
				this.tweens.splice( i, 1 );
			}
		}
		this.fps = Math.floor( tween.actualFrames / ( ( new Date()- tween.startTime ) / 1000 ) );
		if ( this.fps < 20 ) this.fps = 20;
		tween.end( tween );
		this.stop();
	},
	
	start: function()
	{
    	if ( this.thread === null )
    	{
	  		this.thread = setInterval( DSFX.util.fix( this, this.tween ), 0 );
    	}
	},
	
	stop: function()
	{
		if ( this.tweens.length == 0 )
		{
			clearInterval( this.thread );
			this.thread = null;
		}
	},
   
   	tween: function() 
   	{
		for ( var i = 0, tweenCount = this.tweens.length; i < tweenCount; ++i ) 
		{
         	var tween = this.tweens[i];
         	if ( !tween || !tween.tweened ) { continue }
         	if ( tween.currentFrame < tween.totalFrames || tween.totalFrames === null )
         	{
				tween.currentFrame += 1;
            	this.correctFrame( tween );   
            	tween.actualFrames +=1;
            	tween.tween( tween.easement( tween.currentFrame, 0, 1, tween.totalFrames ) );
         	}
         	else 
         	{
		 		this.unregister( tween );
         	}
   		}
	},
	
	correctFrame: function( tween )
	{
		var frames = tween.totalFrames,
      		frame = tween.currentFrame,
      		expected = ( tween.currentFrame * tween.duration * 1000 / tween.totalFrames ),
      		elapsed = ( new Date() - tween.startTime ),
      		tweak = 0;

      	if ( elapsed < tween.duration * 1000 ) // check if falling behind
      	{
         	tweak = Math.round( ( elapsed / expected - 1 ) * tween.currentFrame );
      	}
      	else // went over duration, so jump to end
      	{
         	tweak = frames - ( frame + 1 );
      	}
      	
      	if ( tweak > 0 && isFinite( tweak ) ) // adjust if needed
        {
         	if ( tween.currentFrame + tweak >= frames ) // dont go past last frame
         	{
            	tweak = frames - ( frame + 1 );
         	}
         	
         	tween.currentFrame += tweak;
      	}
	}
};